//
//  NetworkingTool.m
//  KEREN
//
//  Created by MW on 2023/3/8.
//

#import "NetworkingTool.h"
#import "NSDictionary+Expand.h"
@implementation NetworkingTool

+(NSString *)codeToString:(int)code{
    if(code == 1005){
        return @"验证码为空";
    }else if(code == 1006){
        return @"验证码错误";
    }else if(code == 1007){
        return @"验证码获取错误";
    }else if(code == 1008){
        return @"未找到有效数据";
    }
    return nil;
}

// TODO delete
+ (NSString *)buildQueryWithDictionary:(NSDictionary *) dictionary {
    NSMutableArray *query = [NSMutableArray array];
    for (NSString *key in [dictionary allKeys]) {
        id value = dictionary[key];
        [query addObject:[NSString stringWithFormat:@"%@=%@",
                          key,value]];
    }
    return [query componentsJoinedByString:@"&"];
}


+ (NSURLSessionDataTask *)POST:(NSString *)url parameters:(id)parameters isDeviceUrl:(BOOL)isDeviceUrl success:(successBlock)success failure:(failureBlock)failure{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];//[AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"text/plain",@"application/json",@"text/javascript",@"text/xml", nil];
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 30.0;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    UserInfo *user = USERINFO;
    if(user.token && user.token.length > 0){
        NSString *token = [NSString stringWithFormat:@"Bearer %@",user.token];
        [manager.requestSerializer setValue:token forHTTPHeaderField:@"Authorization"];
    }
    if(![url hasPrefix:@"http"]){
        if(isDeviceUrl){
            url = [NSString stringWithFormat:@"%@%@",BaseDeviceUrl,url];
        }else{
            url = [NSString stringWithFormat:@"%@%@",BaseUrl,url];
        }
    }
    long long now_timestamp = [[NSDate date] timeIntervalSince1970];
    NSString *fullUrl = [[NSString stringWithFormat:@"%@?", url] stringByAppendingString:[self buildQueryWithDictionary:parameters]];
    return [manager POST:url parameters:parameters headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        long long end_request_time = [[NSDate date] timeIntervalSince1970];
        DDLogInfo(@"请求方法:POST,开始时间:%lld,结束请求时间:%lld,请求路径:%@, 请求结果:%@",now_timestamp,end_request_time,fullUrl,responseObject);
        [[KRAlartManager shareInstance] hidenLodingImageView];
        int code = [responseObject intForDict:@"code"];
        if(code == 0){
            success(responseObject,task);
        }else{
            if(![url containsString:Device_send_cmd] && ![url containsString:Device_signal_send_msg]){
                NSString *errorStr = [self codeToString:code];
                [[KRAlartManager shareInstance] hidenLodingImageView];
                [[KRAlartManager shareInstance] showErrorAlert:responseObject[@"msg"]];
            }
            success(responseObject,task);
        }
        
//        if (![responseObject isKindOfClass:[NSDictionary class]]) {
//            NSString *sr = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
//            NSData *data = [sr dataUsingEncoding:NSUTF8StringEncoding];
//            NSDictionary *jsonDic = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//            if (jsonDic) {
//                if([jsonDic[@"code"] intValue] == 0){
//                    [[KRAlartManager shareInstance] hidenLodingImageView];
//                    success(jsonDic,task);
//                }else{
//                    [[KRAlartManager shareInstance] hidenLodingImageView];
//                    [[KRAlartManager shareInstance] showErrorAlert:jsonDic[@"msg"]];
//                    success(jsonDic,task);
//                }
//            }else{
//                success(sr,task);
//            }
//        }else{
//            if([responseObject[@"code"] intValue] == 0){
//                success(responseObject,task);
//            }else{
//                if(![url containsString:Device_send_cmd] && ![url containsString:Device_signal_send_msg]){
//                    [[KRAlartManager shareInstance] hidenLodingImageView];
//                    [[KRAlartManager shareInstance] showErrorAlert:responseObject[@"msg"]];
//                }
//                success(responseObject,task);
//            }
//        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DDLogInfo(@"请求error:%@",error);
        [[KRAlartManager shareInstance] hidenLodingImageView];
        if([task.response isKindOfClass:[NSHTTPURLResponse class]]){
            NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
            if (response.statusCode == 401) {
                [[KRAlartManager shareInstance] showErrorAlert:@"登录过期"];
                [[UserInfoManager sharedInstance] tokenloginOut];
            }else{
               /// [[KRAlartManager shareInstance] showErrorAlert:@"请求失败，请稍后再试"];
            }
        }else{
            AFNetworkReachabilityManager *netManger = [AFNetworkReachabilityManager sharedManager];
            if(netManger.networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable){
                [[KRAlartManager shareInstance] showErrorAlert:@"暂无网络,请稍后再试"];
            }
        }
        if(failure) failure(error,task);
    }];
}

+ (NSURLSessionDataTask *)GET:(NSString *)url parameters:(id)parameters isDeviceUrl:(BOOL)isDeviceUrl success:(successBlock)success failure:(failureBlock)failure{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];//[AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"text/plain",@"application/json",@"text/javascript",@"text/xml", nil];
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 30.0;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    if(![url hasPrefix:@"http"]){
        if(isDeviceUrl){
            url = [NSString stringWithFormat:@"%@%@",BaseDeviceUrl,url];
        }else{
            url = [NSString stringWithFormat:@"%@%@",BaseUrl,url];
        }
    }
    UserInfo *user = USERINFO;
    if(user.token && user.token.length > 0){
        NSString *token = [NSString stringWithFormat:@"Bearer %@",user.token];
        [manager.requestSerializer setValue:token forHTTPHeaderField:@"Authorization"];
    }
    long long now_timestamp = [[NSDate date] timeIntervalSince1970];
    NSString *fullUrl = [[NSString stringWithFormat:@"%@?", url] stringByAppendingString:[self buildQueryWithDictionary:parameters]];
    return [manager GET:url parameters:parameters headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        long long end_request_time = [[NSDate date] timeIntervalSince1970];
        DDLogInfo(@"请求方法:GET,开始时间:%lld,结束请求时间:%lld,请求路径:%@, 请求结果:%@",now_timestamp,end_request_time,fullUrl,responseObject);
        if (![responseObject isKindOfClass:[NSDictionary class]]) {
            NSString *sr = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
            NSData *data = [sr dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary *jsonDic = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            if (jsonDic) {
                success(jsonDic,task);
            }else{
                success(sr,task);
            }
        }else{
            success(responseObject,task);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DDLogInfo(@"请求error:%@",error);
        if([task.response isKindOfClass:[NSHTTPURLResponse class]]){
            NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
            if (response.statusCode == 401) {
                [[KRAlartManager shareInstance] showErrorAlert:@"登录过期"];
                [[UserInfoManager sharedInstance] tokenloginOut];
            }
        }
        if(failure) failure(error,task);
        
    }];
}




@end
